<?php

namespace Admin\Controller;

use Utuo\BackgroundController;
use Utuo\Phpass;

class LoginController extends BackgroundController {
	// 登录地址
	public function indexAction() {
		layout(false);
		$this->display();
	}
	
	// 登录提交
	public function loginAction() {
		$email = I('email', '', 'htmlspecialchars');
		$password = I('password', null, false);
		$verify = I('verify');

		// 验证码
		if(!APP_DEBUG){  //如果不是生产环境
			if(!check_verify($verify,2)){
				$data['error'] = 1;
				$data['message'] = '验证码不正确';
				$this->ajaxReturn($data);
			}
		}

		
		$admin = M('admin')->where("email='%s' AND is_deleted=0", $email)->find();
		
		if (empty($admin)) {
			$data['error'] = 1;
			$data['message'] = '登录账号不存在';
		} else {
			if (Phpass::check($password, $admin['password'])) {
				if ($admin['status'] == 0) {
					$data['error'] = 1;
					$data['message'] = '禁止登录';
				} else {
					$data['error'] = 0;
					$data['message'] = '登录成功';
					$wdata = array();
					C("USER_AUTH_KEY") and $wdata[C("USER_AUTH_KEY")] = $admin['id'];
					$this->setLogin($admin['id'], $admin['name'], $wdata);
					$adminData = array(
							'last_login_time' => time(),
							'last_login_ip' => get_client_ip(),
							'login_count' => $admin['login_count'] + 1
					);
					M('admin')->where("id=" . $admin['id'])->save($adminData);
				}
			} else {
				$data['error'] = 1;
				$data['message'] = '登录密码不正确';
			}
		}
		$this->ajaxReturn($data);
	}
	
	// 退出登录
	public function logoutAction() {
		$this->setLogout();
		$this->redirect('Admin/login/index', null, 1, '已经退出，转到登录页面……');
	}
	
	// 验证码
	public function verifyAction(){
		parent::createVerify(2);
	}
}